package org.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.example.config.ApiConfig;
import org.example.entity.requestbody.KeyFilter;
import org.example.util.HttpClientUtil;
import org.example.util.JsonUtil;
import org.example.util.Result;
import org.example.util.constantUtil.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;

import static org.example.enums.ResultCode.FAIL;
import static org.example.enums.ResultCode.SUCCESS;

@Service
@Slf4j
public class EntityQueryService {
    @Autowired
    private ApiConfig apiConfig;
    private static final ClassPathResource resource = new ClassPathResource("entityQuery.json");

    public Result entityQuery(List<KeyFilter<?>> keyFilters, String token){
        Result filterResult=getJsonString(keyFilters);
        if(!filterResult.getSuccess()) return filterResult;

        JSONObject jsonObject=(JSONObject) filterResult.getData();

        // 3. 按页依次查询结果
        Map<String,String> devices=new HashMap<>();  // imei-uuid
        String url=apiConfig.entityQueryApi();
        // 3.1第一次查询
        String[] resultStr= HttpClientUtil.post_data(url,jsonObject,token);
        int totalPages=0;
        int page=jsonObject.getJSONObject("pageLink").getInteger("page");
//        System.out.println("start page:"+jsonObject.getJSONObject("pageLink").getInteger("page"));
        // 3.2循环按页查询
        while(true){
            if(resultStr[0]==null || Integer.parseInt(resultStr[0])!=200){
                log.error("EntityQuery ERROR: code:"+resultStr[0]+" result:"+resultStr[1]);
                try{//错误但是返回json格式
                    //尝试拿数据
                    JSONObject jsonResult = JSONObject.parseObject(resultStr[1]);
                    log.info(jsonResult.toString());
                    String msg=jsonResult.get("message").toString();
                    log.error(msg);
                    return Result.fail(msg);
                } catch (Exception e){//错误而且返回的不是JSON格式
                    log.error("msg: "+resultStr[1]);
                    return Result.fail(resultStr[1]);
                }
            }
            totalPages++;
            // 3.2.1 获取设备列表
            JSONObject jsonResult = JSONObject.parseObject(resultStr[1]);
            JSONArray dataList=jsonResult.getJSONArray("data");
            // 将所有设备添加到结果Set
            for(int i=0;i<dataList.size();i++){
                // 打印imei:uuid信息
//                System.out.println("alarm device "
//                        +dataList.getJSONObject(i).getJSONObject("latest").getJSONObject("ENTITY_FIELD").getJSONObject("name").get("value")+":"
//                        +dataList.getJSONObject(i).getJSONObject("entityId").get("id"));

                if(dataList.getJSONObject(i).getJSONObject("entityId").get("id")!=null &&
                        dataList.getJSONObject(i).getJSONObject("latest").getJSONObject("ENTITY_FIELD").getJSONObject("name").get("value")!=null){
                    devices.put(dataList.getJSONObject(i).getJSONObject("latest").getJSONObject("ENTITY_FIELD").getJSONObject("name").get("value").toString(),  // imei
                            dataList.getJSONObject(i).getJSONObject("entityId").get("id").toString());  // uuid
                }
            }

            // 3.2.2判断是否有还有下一页
            if(!Boolean.parseBoolean(jsonResult.get("hasNext").toString())){//最后一页
                System.out.println("Alarm最后一页啦，page:"+page+" totalPages:"+totalPages);
                break;
            }
            // 修改请求体中pageLink的当前页page的值，url不变
            page++;
            jsonObject.getJSONObject("pageLink").put("page",page);
//            System.out.println("current page:"+jsonObject.getJSONObject("pageLink").getInteger("page"));
            resultStr=HttpClientUtil.post_data(url,jsonObject,token);//String 格式获取结果, [0]为statusCode，[1]为结果(结果可能不是json)
            if(resultStr==null || Integer.parseInt(resultStr[0])!=200){
                log.error("Cannot get Alarm device, resultStr:{}",resultStr);
            }
        }
        log.info("EntityQuery deviceNum:{}",devices.size());  // 打印设备数量信息
        return Result.ok(devices);

    }
    public static Result getJsonString(List<KeyFilter<?>> keyFilters){
        InputStream inputStream = null;
        try {
            inputStream = resource.getInputStream();
        } catch (Exception e) {
            log.error("Cannot get json file! Exception:",e);
            return Result.fail("Cannot get json file!");
        }
        String jsonString = JsonUtil.readJsonFile(inputStream);
        JSONObject jsonObject= JSON.parseObject(jsonString);
        // 必需的两个参数判断
        if(jsonObject.getJSONArray("keyFilters")==null){
            log.error("KeyFilters doesn't exist, json:{}",jsonObject.toString());
            return Result.fail("KeyFilters doesn't exist");
        }
        if(jsonObject.get("pageLink")==null || jsonObject.getJSONObject("pageLink").getInteger("page")==null){
            log.error("PageLink doesn't exist, json:{}",jsonObject.toString());
            return Result.fail("PageLink doesn't exist");
        }

        // 2.将KeyFilters添加到请求体框架，从而构造完整的请求体
        for (KeyFilter<?> keyFilter : keyFilters) {
            // 添加到keyFilters
            jsonObject.getJSONArray("keyFilters").add(JSONObject.toJSON(keyFilter));
        }

        return Result.ok(jsonObject);
    }

}
